package com.css.zfzx.fxpg.modules.picture.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.components.attach.repository.entity.SysAttachmentEntity;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.ServerUtil;
import com.css.zfzx.fxpg.modules.attach.FxAttachmentRepository;
import com.css.zfzx.fxpg.modules.picture.repository.FxPictureNativeRepository;
import com.css.zfzx.fxpg.modules.picture.repository.FxPictureRepository;
import com.css.zfzx.fxpg.modules.picture.repository.entity.FxPictureEntity;
import com.css.zfzx.fxpg.modules.picture.service.FxPictureService;
import com.css.zfzx.fxpg.modules.picture.viewobjects.FxPictureQueryParams;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.fxpg.modules.picture.viewobjects.FxPictureVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * @author leon
 * @date 2020-11-17
 */
@Service
@Slf4j
@PropertySource("classpath:platform-config.yml")
public class FxPictureServiceImpl implements FxPictureService {

    @Value("${role.superCode}")
    private String superCode;
    @Value("${role.provinceCode}")
    private String provinceCode;
    @Value("${role.cityCode}")
    private String cityCode;
    @Value("${role.areaCode}")
    private String areaCode;

    @Autowired
    private FxPictureRepository fxPictureRepository;
    @Autowired
    private FxPictureNativeRepository fxPictureNativeRepository;
    @Autowired
    FxAttachmentRepository attachmentRepository;

    @Override
    public JSONObject queryFxPictures(FxPictureQueryParams queryParams, int curPage, int pageSize) {
        Page<FxPictureEntity> fxPicturePage = this.fxPictureNativeRepository.queryFxPictures(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxPicturePage);
        return jsonObject;
    }


    @Override
    public FxPictureEntity getFxPicture(String id) {
        FxPictureEntity fxPicture = this.fxPictureRepository.findById(id).orElse(null);
        return fxPicture;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxPictureEntity saveFxPicture(FxPictureEntity fxPicture) {
        String uuid = UUIDGenerator.getUUID();
        fxPicture.setId(uuid);
        String userId = PlatformSessionUtils.getUserId();
        // 若省为空，则根据当前登录用户赋值省市区（主要为Excel导入数据时用到）
        if (StringUtils.isNotBlank(fxPicture.getProvince())) {
            List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
            // 是否为超级管理员
            boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
            // 是否为省级管理员
            boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
            // 是否为市级管理员
            boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
            // 是否为区级管理员
            boolean containtRoleArea = ServerUtil.isContaintRole(roles, areaCode);
            if (!containtRole) {
                // 省级管理员
                if (containtRolePro) {
                    DivisionEntity divisionEntity = ServerUtil.getDivisionEntity();
                    fxPicture.setProvince(divisionEntity.getDivisionName());
                }
                // 市级管理员
                if (containtRoleCity) {
                    DivisionEntity cityDivisionEntity = ServerUtil.getDivisionEntity();
                    String city = cityDivisionEntity.getDivisionName();
                    String provinceDivisionId = cityDivisionEntity.getParentId();
                    String province = PlatformAPI.getDivisionAPI().getDivisionById(provinceDivisionId).getDivisionName();
                    fxPicture.setProvince(province);
                    fxPicture.setCity(city);
                }
                // 区级管理员
                if (containtRoleArea) {
                    DivisionEntity areaDivisionEntity = ServerUtil.getDivisionEntity();
                    String area = areaDivisionEntity.getDivisionName();
                    String cityDivisionId = areaDivisionEntity.getParentId();
                    DivisionEntity cityDivisionEntity = PlatformAPI.getDivisionAPI().getDivisionById(cityDivisionId);
                    String city = cityDivisionEntity.getDivisionName();
                    String provinceDivisionId = cityDivisionEntity.getParentId();
                    String province = PlatformAPI.getDivisionAPI().getDivisionById(provinceDivisionId).getDivisionName();
                    fxPicture.setProvince(province);
                    fxPicture.setCity(city);
                    fxPicture.setArea(area);
                }
            }
        }
        String user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId).getUserName();
        fxPicture.setCreateUser(user);
        fxPicture.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxPictureRepository.save(fxPicture);
        return fxPicture;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxPictureEntity updateFxPicture(FxPictureEntity fxPicture) {
        fxPicture.setUpdateUser(PlatformSessionUtils.getUserId());
        fxPicture.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxPicture.getId();
        FxPictureEntity one = fxPictureRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxPicture, one);
        this.fxPictureRepository.save(one);
        return fxPicture;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxPictures(List<String> ids) {
        List<FxPictureEntity> fxPictureList = this.fxPictureRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxPictureList) && fxPictureList.size() > 0) {
            for (FxPictureEntity fxPicture : fxPictureList) {
                String attachId = fxPicture.getAttachId();
                if (StringUtils.isNotBlank(attachId)) {
                    try {
                        SysAttachmentEntity file = PlatformAPI.getAttachmentAPI().getFile(attachId);
                        if (file != null) {
                            PlatformAPI.getAttachmentAPI().deleteFile(attachId);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                this.fxPictureRepository.delete(fxPicture);
            }
        }
    }

    @Override
    @Transactional
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置解析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxPictureVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxPictureVO.class, params);
            List<FxPictureVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxPictureVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxPictureVO pictureVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + pictureVO.getRowNum() + "行" + pictureVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 保存Excel数据
     *
     * @param list
     */
    private void saveExcel(List<FxPictureVO> list) {
        FxPictureEntity pictureEntity = new FxPictureEntity();
        for (FxPictureVO pictureVO : list) {
            BeanUtils.copyProperties(pictureVO, pictureEntity);
            String attchName = pictureVO.getAttchFileName();
            if (StringUtils.isNotBlank(attchName)) {
                // 根据文件名称获取附件表信息
                List<SysAttachmentEntity> attachmentEntities = attachmentRepository.findByAttachNameAndIsValid(attchName, "1");
                if (attachmentEntities.size() > 0) {
                    String attachId = attachmentEntities.get(0).getAttachId();
                    pictureEntity.setAttachId(attachId);
                    pictureEntity.setAttchName(attchName);
                }
            }
            this.saveFxPicture(pictureEntity);
        }
    }
}
